<?php
/**
 * @file function.php
 * @version 0.1
 * @desc 一些公用函数
 * 
 */

require_once '../config/kbao_config.inc.php';
if (! function_exists ( 'json_encode' ))
	require_once 'jsonwrapper/jsonwrapper.php';
session_start();
	
/**
 * 如果登录成功，返回true
 *
 * @param String $user_id
 * @param String $sessionKey
 * 
 * @return String
 */
function isLogin($user_id, $sessionKey) {
	$login = false;
	$nick = '';
	
	$conn = &ADONewConnection ( 'mysqli' );
	$conn->debug = false;
	$conn->Connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	if (! $conn) {
		//$msg = 4;
		die ( "Mysql 连接失败！" );
	}
	//	$conn->Execute('SET NAMES UTF8');
	//	$ADODB_FETCH_MODE = ADODB_FETCH_ASdSOC;
	$re = $conn->Execute ( "CALL `".DB_NAME_AUTH."`.`sp_account_login`('{$user_id}', '{$sessionKey}',\"session\")" );
	if ($re) {
		$uin = $re->fields ['chk_uin'];
		$nick = $re->fields ['chk_nick'];
			
		if ($uin == $user_id) $login = true;
	}
	$re->Close ();
	$conn->Close ();
	
	if ($login == false) {
		$login = sessionCheckLogin($user_id);
		if ($login){
			$uin = $_SESSION['account_arr']['chk_uin'];
			$nick = $_SESSION['account_arr']['chk_nick'];
		}
	}
	
	if ($login){
		$nick = iconv ( 'GB2312', 'UTF-8', $nick );
		if ( mb_strlen($nick, 'UTF-8') > 5 ) {
			$nick = cut_str($nick, 5, 0, 'UTF-8');
		}	
	}
	
	return array ('login' => $login, 'user_id' => $uin, 'user_nick' => $nick );

} //END func isLogin

/**
 * 判断Session登陆,用户自服务后台
 *
 * @param Int $user_id
 * @return Boolean
 */
function sessionCheckLogin($user_id) {
	if (!empty($user_id)){
		for ($i = 0; $i < 2; $i++) {
			if (!isset ($_SESSION['account_arr'][$i])) {
				return false;
			}
		}
		return true;
	}else return false;
} // END func sessionCheckLogin

/**
 * 得到配置选项
 * 
 * @return Array
 *
DELIMITER //
DROP PROCEDURE IF EXISTS bus_option //
CREATE PROCEDURE bus_option()
	SELECT `ID` , `name` , `note` , `value` FROM `bus_option`;
 //
DELIMITER ;
 * 
 */
function getOption() {
	$conn = &ADONewConnection ( 'mysqli' );
	$conn->debug = false;
	$conn->Connect ( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME );
	if (! $conn) {
		//$msg = 4;
		die ( "Mysql 连接失败！" );
	}
	$conn->Execute ( 'SET NAMES UTF8' );
	$data = dbGetListByProcedure ( $conn, "CALL bus_option()" );
	$result = array ();
	foreach ( $data as $v ) {
		$result [$v ['name']] = $v ['value'];
	}
	
	$conn->Close ();
	return $result;
} //END func getOption


/**
 * 调用存储过程，并返回一个数据集
 *
 * @param ADONewConnection $db
 * @param String $Sql
 * @param  String $ListKey
 * @return Array
 */
function dbGetListByProcedure($db, $Sql, $ListKey = "") {
	$DataList = array ();
	
	$rs = $db->Execute ( $Sql );
	if ($rs) {
		if ($ListKey == '') {
			while ( ! $rs->EOF ) {
				$Row = $rs->fields;
				
				$DataList [] = $Row;
				$rs->MoveNext ();
			}
		} else {
			while ( ! $rs->EOF ) {
				$Row = $rs->fields;
				
				$DataList [$Row [$ListKey]] = $Row;
				$rs->MoveNext ();
			}
		}
		
		// 请注意必须执行以下指令，否则当程序再次执行SQL查询时会出错  
		while ( $rs->NextRecordSet () )
			;
		
	// 执行以上语句后，不需要再执行如下的语句了         
	//$rs->Close();
	}
	if (! is_array ( $DataList ))
		return array ();
	return $DataList;
} //END func dbGetListByProcedure


/*
Utf-8、gb2312都支持的汉字截取函数
cut_str(字符串, 截取长度, 开始长度, 编码);
编码默认为 utf-8
开始长度默认为 0
*/
function cut_str($string, $sublen, $start = 0, $code = 'UTF-8') {
	if ($code == 'UTF-8') {
		$pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/";
		preg_match_all ( $pa, $string, $t_string );
		if (count ( $t_string [0] ) - $start > $sublen)
			return join ( '', array_slice ( $t_string [0], $start, $sublen ) ); // . "...";
		return join ( '', array_slice ( $t_string [0], $start, $sublen ) );
	} else {
		$start = $start * 2;
		$sublen = $sublen * 2;
		$strlen = strlen ( $string );
		$tmpstr = '';
		
		for($i = 0; $i < $strlen; $i ++) {
			if ($i >= $start && $i < ($start + $sublen)) {
				if (ord ( substr ( $string, $i, 1 ) ) > 129) {
					$tmpstr .= substr ( $string, $i, 2 );
				} else {
					$tmpstr .= substr ( $string, $i, 1 );
				}
			}
			if (ord ( substr ( $string, $i, 1 ) ) > 129)
				$i ++;
		}
		if (strlen ( $tmpstr ) < $strlen)
			$tmpstr .= ''; // "...";
		return $tmpstr;
	}
} //END cut_str


?>